import request from 'request';
import path from "path";

const SEND_URL = 'https://api.push.hicloud.com/v3/388421841222001047/messages:send';


export class PushMessageService {
  /**
   * 发送推送通知
   * @param pushTokens
   * @param authorization
   * @returns
   */
  static sendMessage(pushTokens: string[], authorization: string) {

    // 构建header头
    const headers = {
      "push-type": 0,
      "Authorization": authorization
    };
    // 构建请求体数据
    const RequestBodyJsonPostData = {
      "payload": {
        "notification": {
          "category": "MARKETING",
          "title": "找自己",
          "body": "pushkit普通通知内容",
          // "profileId": "liaowenjing",
          "style": 3,
          "inboxContent": [
            "1. 通知栏消息样式",
            "2. 通知栏消息提醒方式和展示方式",
            "3. 通知栏消息语言本地化"
          ],
          "image": "https://sanjitian-1256310189.cos.ap-chengdu.myqcloud.com/huaweikey/test22.jpg",
          // "badge": {
          //   "addNum": 1,
          //   "setNum": 99
          // },
          "clickAction": {
            "actionType": 0,
            "data": { "pagePath": "CloudFunction" }
          },
          "notifyId": 12345
        }
      },
      "target": {
        "token": pushTokens
      },
      "pushOptions": {
        "testMessage": true,
        "ttl": 86400
      }
    }


    return new Promise((resolve, reject) => {
      // 使用POST方式发送请求
      request.post({
        url: SEND_URL,
        form: JSON.stringify(RequestBodyJsonPostData),
        headers: headers
      }, function (err, httpResponse, body) {
        console.log(`sendMessage request: ${httpResponse.statusMessage}`)
        const result = JSON.parse(body);
        if (httpResponse.statusCode == 200 && (result.code === "80000000" || result.code === "80100000")) {
          console.log(`sendMessage success: ${JSON.stringify(body)}`)
          resolve(result.msg);
        } else {
          reject(err);
        }
      })
    });


  }

  /**
   * 获取 Authorization
   * @param param1
   * @param param2
   * @returns
   */
  static getAuthorizationToken(): string {
    // 依赖：npm i jsonwebtoken
    const jwt = require('jsonwebtoken');
    const fs = require('fs');
    // 加载RSA私钥
    // 实际开发时请从服务账号密钥文件中读取private_key保存在.pem中，参考“基于服务账号生成鉴权令牌中创建服务账号密钥文件。
    // const PRIVATE_KEY =
    //   fs.readFileSync('https://sanjitian-1256310189.cos.ap-chengdu.myqcloud.com/huaweikey/private_key.pem', 'utf8');

    // 添加异常处理
    let PRIVATE_KEY;
    try {
      PRIVATE_KEY = fs.readFileSync(
        path.resolve(__dirname, 'private_key.pem'),
        'utf8'
      );

      // 实际开发时请从服务账号密钥文件中读取sub_account
      const ISS = '113684591';
      // 实际开发时请从服务账号密钥文件中读取key_id
      const KID = 'c3ab09b563ac4bd48c264c0d08c9b981';
      // 实际开发时请将公网地址存储在配置文件或数据库
      const AUD = 'https://oauth-login.cloud.huawei.com/oauth2/v3/token';
      // 自定义Header
      const header = {
        alg: 'PS256', // 建议使用PS256算法
        kid: KID,
        typ: 'JWT'    // 类型为JWT
      };
      // 创建JWT载荷
      const payload = {
        iss: ISS, // 实际开发时请从服务账号密钥文件中读取sub_account
        aud: AUD, // 实际开发时请将公网地址存储在配置文件或数据库
        iat: Math.floor(Date.now() / 1000),
        exp: Math.floor(Date.now() / 1000) + 3600
      };
      // 签署JWT
      const token: string = jwt.sign(payload, PRIVATE_KEY, {
        algorithm: 'PS256', header: header
      });
      console.log("Generated JWT:", token);
      return "Bearer " + token;
    } catch (error) {
      console.error('密钥加载失败:', error);
      throw new Error('身份验证配置错误');
    }

  }
}

